<!-- 专家信息管理 -->
<template>
  <div>
    <ContainerSlot>
      <!-- 搜索 -->
      <template slot="searchModule">
        <SearchForm :label-width="labelWidth" :form-config="formConfig" :form-data="formData" :slot-list="slotList">
          <template slot="searchBtn">
            <el-button type="primary" @click.prevent="submitForm()">查询</el-button>
          </template>
        </SearchForm>
      </template>
      <!-- 操作 -->
      <template slot="operationModule">
        <el-button type="primary" plain @click="addExpert">添加</el-button>
      </template>
      <!-- 内容 -->
      <template slot="contentModule">
        <div v-show="expertInfoList.length > 0" class="container">
          <div v-for="item in expertInfoList" :key="item.personId" class="containerItem">
            <div class="header">
              <div class="headpicture">
                <img :src="item.headUrl" alt="">
              </div>
              <div class="personInfo">
                <div class="name">{{ item.name }}</div>
                <div class="description">
                  <div class="degree">{{ item.position }}</div>
                  <div class="field">
                    擅长领域：{{ item.area }}
                  </div>
                </div>
              </div>
            </div>
            <div class="middle">
              <div class="title">专家介绍：</div>
              <div class="introduceInfo">
                {{ item.introduce }}
              </div>
            </div>
            <div class="footer">
              <el-button type="primary" size="mini" style="float: right;margin-left: 20px;"
                @click="del(item)">删除</el-button>
              <el-button type="primary" plain size="mini" style="float: right;" @click="edit(item)">修改</el-button>
            </div>
            <div class="decoration" />
          </div>
        </div>
        <div v-show="expertInfoList.length == 0" class="nodata">
          暂无数据~
        </div>
      </template>
      <template slot="footerModule">
        <el-pagination :current-page="currentPage" background :page-size="pageSize" :page-sizes="[10, 20, 30]"
          layout=" prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </template>
    </ContainerSlot>
    <!-- 对话框 -->
    <el-dialog :close-on-click-modal='false' :title="`${title}专家信息`" :visible.sync="dialogFormVisible" top="30vh"
      @close="cancle">
      <el-form ref="ruleForm" :inline="true" :model="form" :rules="rules">
        <!-- prop="name" -->
        <el-form-item label="专家姓名：" :label-width="formLabelWidth" prop="name">
          <el-select v-model="form.userId" placeholder="请选择">
            <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="专家照片：" :label-width="formLabelWidth" class="photo">
          <el-upload ref="upload" v-loading="uploading" class="upload-demo" action="" :limit="limits"
            :file-list="uploadFileList" :http-request="handlerFile" :on-exceed="handleExceed">
            <el-button type="primary" style="width: 175px;background: #BEDFFF;color: #0480FB">添加照片</el-button>
            <!-- v-if="title=='添加'" <img v-else :src="uploadFileList[0].url" alt="" style="width: 50px; height: 50px;"> -->
          </el-upload>
        </el-form-item>
        <el-form-item label="专家领域：" :label-width="formLabelWidth" prop="area">
          <el-input v-model="form.area" />
        </el-form-item>
        <el-form-item label="专家职称：" :label-width="formLabelWidth" prop="position">
          <el-input v-model="form.position" />
        </el-form-item>
        <el-form-item label="专家介绍：" :label-width="formLabelWidth" prop="introduce">
          <el-input v-model="form.introduce" type="textarea" style="width: 485px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ContainerSlot from '@/components/Container'
import SearchForm from '@/components/Form'
// import CategoryBar from '@/components/CategoryBar'
import expertInfoApi from '@/api/specialist-consultation/expert-management/expert-information-management/index' // 查询/添加/修改/删除
import DocumentApi from '@/api/document'
import config from '@/api/config'
import SystemUserManagement from '@/api/module/system-user-management'   // 专家管理

export default {
  name: '',
  components: { ContainerSlot, SearchForm },
  data () {
    var validateArea = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('专家领域不能为空'))
      } else {
        callback()
      }
    }
    var validatePosition = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('排班时间不能为空'))
      } else {
        callback()
      }
    }
    var validateIntroduce = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('排班介绍不能为空'))
      } else {
        callback()
      }
    }
    return {
      options: [], // 专家姓名
      expertInfoList: [],
      total: 1,
      currentPage: 1,
      pageSize: 10,
      title: '添加',
      uploadFileList: [],
      uploading: false,
      limits: 1,
      // 搜索框距离左侧位置
      labelWidth: '100px',
      // 表单配置
      formConfig: [
        {
          label: '专家名称',
          prop: 'name1',
          type: 'input',
          width: '150px'
        }
      ],
      // 查询按钮或重置
      slotList: [
        {
          slotName: 'searchBtn'
        }
      ],
      // 表单数据
      formData: {
        name1: ''
      },
      // 控制对话框显示隐藏
      dialogFormVisible: false,
      // 收集数据
      form: {
        name: '',
        area: '',
        position: '',
        introduce: '',
        headUrl: '',
        url: null
      },
      formLabelWidth: '120px',
      rules: {
        // required: true,
        userId: [
          { required: true, message: '请输入专家姓名', trigger: ['blur', 'change'] },
        ],
        // url: [
        //   { required: true,message: '图片不能为空',trigger: ['blur' ,'change']}
        // ],
        area: [
          { required: true, message: '请输入专家领域', trigger: 'blur' },
          { validator: validateArea, trigger: 'change' }
        ],
        position: [
          { required: true, message: '请输入专家职称', trigger: 'blur' },
          { validator: validatePosition, trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入专家介绍', trigger: 'blur' },
          { validator: validateIntroduce, trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    this.getExpertInfoList()
    this.queryUserPageList()
  },
  methods: {
    //获取专家管理中专家信息
    queryUserPageList () {
      SystemUserManagement.queryByCondition({ userType: "expert_user" }).then(res => {
        if (res.code == 200) {
          console.log('res***', res);
          this.options = res.data
          console.log('this.options', this.options);
        } else {
          console.log('失败了');
        }
      })
    },
    // 条件分页查询
    async getExpertInfoList (pages = 1, names = '') {
      if (pages === 0) {
        pages = 1
      }
      const params = {
        page: pages,
        size: this.pageSize,
        condition: {
          name: names
        }
      }
      const res = await expertInfoApi.queryPageByCondition(params)
      if (res.code === 200) {
        this.expertInfoList = res.data.content
        // console.log(res.data, 'res')
        this.total = res.data.totalElements
      }
    },
    handleSizeChange (e) {
      this.pageSize = e
      this.getExpertInfoList()
    },
    handleCurrentChange (e) {
      this.currentPage = e
      this.getExpertInfoList(e)
    },
    // 添加专家
    addExpert () {
      this.reset()
      this.title = '添加'
      this.dialogFormVisible = true
    },
    // 上传图片
    handlerFile (files) {
      this.uploadFileList = []
      const { file } = files
      const dataForm = new FormData()
      dataForm.append('file', file)
      dataForm.append('moduleType', 'EXPERT')
      this.uploading = false
      DocumentApi.getUploadUrl(dataForm).then(res => {
        this.uploading = false
        const filePath = res.data
        const url = config.webServiceUrl + `${filePath}`
        this.uploadFileList.push({ url, name: url })
        this.form.headUrl = url
        this.form.url = url
      }).catch(() => {
        this.uploading = false
        this.$message.error('图片上传失败！')
      })
    },

    // 添加专家
    async confirmAdd () {
      console.log('this.$refs.upload', this.$refs.upload._props.fileList.length);
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {

          this.options.forEach(item => {
            if (Number(item.userId) == Number(this.form.userId)) {
              this.form.name = item.nickName
            }
          })
          if (this.title === '添加') {
            // 
            if (this.$refs.upload._props.fileList.length == 0) {
              this.$message.error('请添加图片')
            } else {
              const res = await expertInfoApi.addExpertInfo(this.form)
              if (res.code === 200) {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getExpertInfoList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            }
          } else {
            const res = await expertInfoApi.editExpertInfo(this.form)
            if (res.code === 200) {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.getExpertInfoList()
            } else {
              this.$message({
                type: 'error',
                message: '修改失败'
              })
            }
          }
        } else {
          if (this.uploadFileList.length === 1) {
            this.form.url = this.uploadFileList[0].headUrl
            this.$refs.ruleForm.clearValidate(['url'])
            // this.confirmAdd()
          }
          return false
        }
      })
    },
    // 修改
    edit (row) {
      console.log(row)
      this.title = '修改'
      this.dialogFormVisible = true
      this.form = { ...row }
      this.form.url = row.headUrl
      this.uploadFileList = [{ url: row.headUrl, name: row.headUrl }]
    },
    del (item) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const params = {}
          const res = await expertInfoApi.delExpertInfo(params, item.personId)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getExpertInfoList(this.expertInfoList.length > 1 ? this.currentPage : this.currentPage - 1)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    categoryBar (item) {
      this.status = ''
      if (item.mark === 'status') this.status = item.value
      this.queryPageList()
    },
    queryPageList () {

    },
    // 重置
    reset () {
      this.form = {}
      this.form.headUrl = ''
      this.form.url = ''
      this.uploadFileList = []
    },
    // 搜索
    submitForm () {
      console.log(this.formData.name1)
      this.getExpertInfoList(undefined, this.formData.name1)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    cancle () {
      this.dialogFormVisible = false
      this.$nextTick(() => {
        this.reset()
        this.$refs.ruleForm.resetFields()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// dialog框header背景色
/deep/ .el-dialog__header {
  background: #0480fb;
}

// 设置dialog框叉号颜色
::v-deep .el-dialog__close {
  color: #fff;
}

// dialog框标题颜色
::v-deep .el-dialog__title {
  color: #fff;
}

// 主体部分滚动条
::v-deep .childModule {
  overflow: auto !important;
}

.container {
  width: 100%;
  height: 100%;

  .containerItem {
    position: relative;
    float: left;
    margin-right: 1%;
    width: 49%;
    height: 270px;
    margin-top: 4px;
    margin-bottom: 19px;
    border-radius: 5px;
    border: 1px solid #d6ebfe;

    .header {
      width: 100%;
      display: flex;
      justify-content: space-between;
      padding: 10px;
      overflow: hidden;
      background: #d6ebfe;
      background: url('~@/assets/specialist-consultation/expert-management/expert-information-management/bj.jpg') 100% 100%;

      .headpicture {
        overflow: hidden;
        width: 79px;
        height: 79px;
        border-radius: 50%;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .personInfo {
        flex: 1;
        margin-left: 19px;
        font-size: 18px;
        font-weight: 500;
        color: #fff;

        .description {
          display: flex;
          margin-top: 10px;

          .degree {
            width: 72px;
            margin-right: 20px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .field {
            height: 41px;
            display: -webkit-box;
            overflow: hidden;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
          }
        }
      }
    }

    .middle {
      display: flex;
      padding: 20px 30px 16px 20px;

      .title {
        height: 22px;
        border-left: 1px solid #0480fb;
        padding-left: 10px;
      }

      .introduceInfo {
        flex: 1;
        height: 93px;
        display: -webkit-box;
        overflow: hidden;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 5;
      }
    }

    .footer {
      padding: 10px 20px;
      background: #edf6ff;
      overflow: hidden;
    }

    .decoration {
      position: absolute;
      top: -4px;
      left: 50%;
      transform: translateX(-50%);
      width: 22px;
      height: 4px;
      background: #0480fb;
      z-index: 6;
    }
  }
}

::v-deep .el-upload-list__item-name {
  // position: relative;
  // left: -30px;
  width: 100%;
}

// 无数据
.nodata {
  position: relative;
  width: 100%;
  // height: 100%;
  text-align: center;
  top: 50%;

}

// ::v-deep .photo {
//   display: block;
// }
</style>
